import Vue from 'vue'
import VueRouter from 'vue-router'
import Register from '@/views/Register.vue'
import Login from '@/views/Login.vue'
import Layout from '@/views/Layout.vue'
import Detail from '@/views/Detail.vue'
import Article from '@/views/Article.vue'
import Collect from '@/views/Collect.vue'
import Like from '@/views/Like.vue'
import User from '@/views/User.vue'
import { getToken } from '@/utils/storage'
import { Toast, Cell, CellGroup } from 'vant'

Vue.use(Cell)
Vue.use(CellGroup)
Vue.use(VueRouter)

const routes = [
  { path: '/register', component: Register },
  { path: '/login', component: Login },
  {
    path: '/',
    redirect: '/article',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  },
  { path: '/detail/:id', component: Detail }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register']
// 导航守卫=>全局前置守卫
router.beforeEach((to, from, next) => {
  // 1.to   你往哪里去
  // 2.from 你从哪里来
  // 3.next() 是否放行，如果next('路径')调用，就是放行 => 放你去想去的页面
  // next(false)表示不放行
  const token = getToken()
  if (token) {
    next()
  } else {
    // 以后白名单越来越多,会导致判断越写越长,可以定义一个数组,把判断页面放进去
    // if (to.path === '/login' || to.path === '/register') {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Toast.fail('您还未等登录,请登录')
      next('/login')
    }
  }
})
// 后置守卫,暂时不学
// router.afterEach

export default router
